package com.csdj.dao;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 数据库的连接工具类
 */
public abstract class BaseDao {


    protected Connection conn;
    protected PreparedStatement psmt;
    protected ResultSet rs;

    //创建C3P0的连接池对象
    ComboPooledDataSource dataSource = new ComboPooledDataSource();

    /**
     * 获取数据库连接对象
     *
     * @return 数据库的连接对象
     */
    public Connection getConnection() {
        Connection connection = null;
        try {
            //从连接池中获取连接对象
            connection = dataSource.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    public ResultSet executeQuery(String sql, Object... params) throws SQLException {
        this.psmt = conn.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            this.psmt.setObject(i + 1, params[i]);
        }
        rs = psmt.executeQuery();
        return rs;
    }

    public int executeUpdate(String sql, Object... params) throws SQLException {
        this.psmt = conn.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            this.psmt.setObject(i + 1, params[i]);
        }
        return psmt.executeUpdate();
    }

    /**
     * 释放资源
     *
     * @param conn 数据库的连接对象
     * @param psmt 预编译对象
     * @param rs   结果集对象
     */
    public void closeAll(Connection conn, PreparedStatement psmt, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }

            if (psmt != null) {
                psmt.close();
            }

            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


}